<?php
/**
 * @author: zhypy<214681832@qq.com>
 * @day: 2020/7/10
 */
declare (strict_types=1);

namespace app\services\pay;


use app\services\user\UserRechargeServices;
use app\services\wechat\WechatUserServices;
use crmeb\services\WechatService;
use crmeb\utils\Str;
use think\exception\ValidateException;

/**
 *
 * Class RechargeServices
 * @package app\services\pay
 */
class RechargeServices
{
    protected $pay;

    /**
     * RechargeServices constructor.
     * @param PayServices $pay
     */
    public function __construct(PayServices $pay)
    {
        $this->pay = $pay;
    }

    public function recharge(int $recharge_id)
    {
        /** @var UserRechargeServices $rechargeServices */
        $rechargeServices = app()->make(UserRechargeServices::class);
        $recharge = $rechargeServices->getRecharge($recharge_id);
        if (!$recharge) {
            throw new ValidateException('订单失效或者不存在');
        }
        if ($recharge['paid'] == 1) {
            throw new ValidateException('订单已支付');
        }
        /** @var WechatUserServices $wechatUser */
        $wechatUser = app()->make(WechatUserServices::class);
        $openid = $wechatUser->uidToOpenid((int)$recharge['uid']);
        if (!$openid) {
            throw new ValidateException('获取用户openid失败,无法支付');
        }
        $site_name = sys_config('site_name');
        $body = Str::substrUTf8($site_name . '--用户充值', 30);
        //, '', 'JSAPI', [
        //            'notify_url' => 'http://' . $_SERVER['HTTP_HOST'] . '/api/recharge/notify'
        //        ]
        return WechatService::jsPay($openid, $recharge['order_id'], $recharge['price'], 'user_recharge', $body);
    }

}
